<?php

namespace app\middleware;

use Tinywan\Jwt\JwtToken;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class AuthCheck implements MiddlewareInterface
{
    public function process(Request $request,callable $next): Response
    {
        $controller = $request->controller;
        $action = $request->action;
        // 反射控制器类，获取白名单
        $ref = new \ReflectionClass($controller);
        $noNeedLogin = $ref->getDefaultProperties()['noNeedLogin'] ?? [];

        // 需要登录验证
        if (!in_array($action, $noNeedLogin)) {
            $userId = JwtToken::getCurrentId();

            if (!$userId) {
                return json(['code' => 0, 'msg' => '请先登录'], 401);
            }

            $user = JwtToken::getUser();
            if (!$user) {
                return json(['code' => 0, 'msg' => '未找到玩家'], 401);
            }

            if (!$user->status) {
                return json(['code' => 0, 'msg' => '账号已被禁用'], 401);
            }

        }

        return $next($request);
    }
}
